import HouseApi from '@/api/house'

const state = {
  allBuilding: [],
  list: [],
  listQuery: { page: 1, limit: 5, count: 0, data: {}}
}

const mutations = {
  SET_ALL: (state, payload) => {
    state.allBuilding = payload
  },
  SET_LISTQUERY: (state, payload) => {
    state.listQuery = payload
  },
  SET_LIST: (state, payload) => {
    console.log(payload, 78)
    state.list = payload.rows
    state.listQuery.count = payload.count
  },
  CHANGE_LIST: (state, payload) => {
    for (const item of state.list) {
      if (item._id === payload._id) {
        item.edit = payload.edit
        break
      }
    }
    state.list = [...state.list]
  }
}
const actions = {
  async getAll({ commit }) {
    const data = await HouseApi.getBuilding()
    console.log(data, 22)
    commit('SET_ALL', data)
  },
  async getHouse({ commit, state }) {
    const data = await HouseApi.getHouse(state.listQuery)
    commit('SET_LIST', data)
  },
  async addHouse(context, payload) {
    return new Promise((resolve, reject) => {
      HouseApi.addHouse(payload).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  async changeCard({ dispatch }, payload) {
    const data = await HouseApi.change(payload)
    console.log(data, 9)
    dispatch('getHouse')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
